import urllib,urllib2,re,xbmcplugin,xbmcgui,os


__plugin__  = "multiflix"
__author__  = "mortael"
__date__    = "17/04/2010"
__version__ = "8"

THUMBNAIL_PATH = os.path.join(os.getcwd().replace( ";", "" ),'resources','media')
tnalogo = os.path.join(THUMBNAIL_PATH, 'tnaflix.png')
emplogo = os.path.join(THUMBNAIL_PATH, 'empflix.png')

def MAIN():
    addDir('TNAFlix - Most Recent','http://www.tnaflix.com/video.php?category=mr',2,tnalogo)
    addDir('TNAFlix - Most Viewed','http://www.tnaflix.com/video.php?category=mv',2,tnalogo)
    addDir('TNAFlix - Top Rated','http://www.tnaflix.com/video.php?category=tr',2,tnalogo)
    addDir('TNAFlix - Full Movies','http://www.tnaflix.com/video.php?category=rd',2,tnalogo)
    addDir('TNAFlix - Categories','http://www.tnaflix.com/channels.php',3,tnalogo)
    addDir('Search TNAFlix','http://www.tnaflix.com/search.php',7,tnalogo)
    addDir('EmpFlix - Most Recent','http://www.empflix.com/browse.php?category=mr',2,emplogo)
    addDir('EmpFlix - Most Viewed','http://www.empflix.com/browse.php?category=mv',2,emplogo)
    addDir('EmpFlix - Top Rated','http://www.empflix.com/browse.php?category=tr',2,emplogo)
    addDir('EmpFlix - Full Movies','http://www.empflix.com/browse.php?category=rd',2,emplogo)
    addDir('EmpFlix - Categories','http://www.empflix.com/categories.php',3,emplogo)
    addDir('Search Empflix','http://www.empflix.com/search.php',7,emplogo)
    addDir('Ellefsworld Full movielist on Empflix','http://ellefsworld.com/pages/choice.html',6,os.path.join(THUMBNAIL_PATH, 'ellefsworld.jpg'))
    
                                       
def getURL(url):
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
    opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14')]
    urllib2.install_opener(opener)
    response = opener.open(url);link=response.read();response.close()
    return link
    

def INDEX(url): 
    link=getURL(url.replace( " ", "%20" ))
    if url.find('tnaflix')>0:
        match=re.compile(r'src="([^"]+jpg)"[^?]+\?viewkey=([^"]+)"\s+?title="([^"]+)".+?screen">([^\r\n]+)',re.IGNORECASE + re.DOTALL + re.MULTILINE).findall(link)
        for thumbnail,url,name,rt in match:
            name = name+' - '+rt
            addDir(name,'http://cdn.tnaflix.com/tnaflv/'+url+'.flv',5,thumbnail)
        try:
            nextp=re.compile(r'<a href="(?:http://www\.tnaflix\.com/)*([^"]+)">next &gt;&gt;</a>',re.IGNORECASE + re.DOTALL + re.MULTILINE).findall(link)
            addDir('-= [ N E X T     P A G E ] =-', 'http://www.tnaflix.com/'+nextp[0], 2, 'http://www.viewista.com/right_arrow.jpg')
        except: pass
    else:
        match=re.compile(r'\?id=([^"]+)"  title="([^"]+)"><img src=" ([^"]+.jpg)".*?length">([^<]+)',re.IGNORECASE + re.DOTALL + re.MULTILINE).findall(link)
        for url,name,thumbnail,rt in match:
            name = name+' - '+rt
            addDir(name,'http://www.empflix.com/view.php?id='+url,5,thumbnail)
        try:
            nextp=re.compile(r'href="([^"]+)">next &gt;&gt;</a></DIV>',re.IGNORECASE + re.DOTALL + re.MULTILINE).findall(link)
            addDir('-= [ N E X T     P A G E ] =-', 'http://www.empflix.com/'+nextp[0], 2, 'http://www.viewista.com/right_arrow.jpg')
        except: pass

def SORTCAT(url):
    dialog = xbmcgui.Dialog()
    sortlist = [xbmc.getLocalizedString(30011),xbmc.getLocalizedString(30012),xbmc.getLocalizedString(30013),xbmc.getLocalizedString(30014),xbmc.getLocalizedString(30015)]
    sort = dialog.select(xbmc.getLocalizedString(30010), sortlist)
    CATEGORIES(url,sort)

def CATEGORIES(url,sorttype):
    link=getURL(url)
    sortlist = [xbmc.getLocalizedString(30011),xbmc.getLocalizedString(30012),xbmc.getLocalizedString(30013),xbmc.getLocalizedString(30014),xbmc.getLocalizedString(30015)]
    change = 'Change Sort: '+ sortlist[sorttype]
    if url.find('tnaflix')>0:
        addDir(change,url,3,tnalogo)
        match=re.compile(r'<a href="(http://www\.tnaflix\.com/[^"]+)" class="catTitle">\s+<img src="([^"]+)" alt="([^"]+)"', re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link)
        sort = ( "being-watched", "most-recent", "most-viewed", "top-rated", "full-length", )[ int(sorttype) ]
        for url,thumbnail,name in match:
            url=url + "/" + sort + "/1"
            addDir(name,url,2,thumbnail)
    else:
        addDir(change,url,3,emplogo)
        match=re.compile(r'<a href="(http://www\.empflix\.com/[^"]+)"><img src="([^"]+)" alt="([^"]+)"', re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link)
        sort = ( "bw", "mr", "mv", "tr", "rd", )[ int(sorttype) ]
        for url,thumbnail,name in match:
            url=url + "&page=1&category=" + sort
            addDir(name,url,2,thumbnail)


def VIDEO(name,url):
    link=getURL(url)
    match=re.compile("<file>([^<]+)", re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link)
    if not match: match=re.compile('"([^"]+)">Download FLV<', re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link)
    if not match: match=re.compile("'file','([^']+)", re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link)
    if not match:
        match2=re.compile("'config', '([^']+)", re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link)
        link2=getURL('http://cdn.empflix.com/'+urllib.unquote(match2[0]))
        match=re.compile("<file>([^<]+)", re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link2)
    for video in match:
        addLink(name,video)


def search(site):
    addDir('New Search',site,8,'DefaultFolder.png')
    try :
        saved_queries = eval( xbmcplugin.getSetting( int(sys.argv[1]), "saved_queries" ) )
    except :
        saved_queries = []
    for query in saved_queries :
        searched = query.replace(' ','+')
        url = site+'?what='+searched
        addDir(query,url,2,'DefaultFolder.png')
        
        
def newsearch(site):
    bla = ''
    kb = xbmc.Keyboard(bla, "Search")
    kb.doModal()
    if (kb.isConfirmed()):
        searchstring = unicode( kb.getText(), "utf-8" )
    try : saved_queries = eval( xbmcplugin.getSetting( int(sys.argv[1]), "saved_queries" ) )
    except : saved_queries = []
    try : saved_queries.index( searchstring )
    except :
        saved_queries.append( searchstring )
        saved_queries.sort()
        xbmcplugin.setSetting( "saved_queries", repr( saved_queries ))
    searched = searchstring.replace(' ','+')
    url = site+'?what='+searched
    INDEX(url)


def ELLEFSWORLD(url): 
    link=getURL(url)
    match=re.compile(r"(\d{5})(?:\1|\s-\s)([^<\n\r]+)", re.DOTALL | re.IGNORECASE | re.MULTILINE).findall(link)
    for url,name in match:
        addDir(name,'http://www.empflix.com/view.php?id='+url,5,'')

        
def get_params():
    param=[]
    paramstring=sys.argv[2]
    if len(paramstring)>=2:
        params=sys.argv[2]
        cleanedparams=params.replace('?','')
        if (params[len(params)-1]=='/'):
            params=params[0:len(params)-2]
        pairsofparams=cleanedparams.split('&')
        param={}
        for i in range(len(pairsofparams)):
            splitparams={}
            splitparams=pairsofparams[i].split('=')
            if (len(splitparams))==2:
                param[splitparams[0]]=splitparams[1]
                                
    return param


def addLink(name,url):
    def Download(url,dest):
            dp = xbmcgui.DialogProgress()
            dp.create("Multiflix Download","Downloading File",url)
            urllib.urlretrieve(url,dest,lambda nb, bs, fs, url=url: _pbhook(nb,bs,fs,url,dp))
    def _pbhook(numblocks, blocksize, filesize, url=None,dp=None):
            try:
                    percent = min((numblocks*blocksize*100)/filesize, 100)
                    print percent
                    dp.update(percent)
            except:
                    percent = 100
                    dp.update(percent)
            if dp.iscanceled():
                    dp.close()
    if xbmcplugin.getSetting(int(sys.argv[1]),"Download Flv") == "true":
            dialog = xbmcgui.Dialog()
            path = dialog.browse(3, 'Choose Download Directory', 'files', '', False, False, '')
            filename = xbmc.makeLegalFilename(path+name+'.flv')
            Download(url,filename)
    thumbnail = xbmc.getInfoImage("ListItem.Thumb")
    liz=xbmcgui.ListItem(name,iconImage="DefaultVideo.png", thumbnailImage=thumbnail)
    liz.setInfo( type="Video", infoLabels={ "Title": name } )
    if xbmcplugin.getSetting(int(sys.argv[1]),"dvdplayer") == "true":
        xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(url, liz)
    else:
        xbmc.Player().play(url, liz)


def addDir(name,url,mode,iconimage):
    u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
    ok=True
    liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
    liz.setInfo( type="Video", infoLabels={ "Title": name } )
    xbmcplugin.setContent( handle=int( sys.argv[ 1 ] ), content="movies" )
    if mode==5:
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
    else: ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
    return ok


params=get_params()
url=None
name=None
mode=None

try:
    url=urllib.unquote_plus(params["url"])
except:
    pass
try:
    name=urllib.unquote_plus(params["name"])
except:
    pass
try:
    mode=int(params["mode"])
except:
    pass

if mode==None or url==None or len(url)<1:
    MAIN()
elif mode==2:
    INDEX(url)
elif mode==3:
    SORTCAT(url)
elif mode==5:
    VIDEO(name,url)
elif mode==6:
    ELLEFSWORLD(url)
elif mode==7:
    search(url)
elif mode==8:
    newsearch(url)

xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
xbmcplugin.endOfDirectory(int(sys.argv[1]))